﻿using BW.Mes.WinForms.Common;
using BW.Mes.WinForms.Properties;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.Login
{
    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {

        string login = Settings.Default.Login;
        string loginUrl = "api/Auth/login";

        public LoginForm()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            //获取账号
            var name = this.txt_userName.Text.Trim();
            //获取密码
            var pwd = this.txt_passWord.Text.Trim();

            // 创建忽略SSL证书验证的HttpClientHandler
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };

            using (HttpClient client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(login);

                // var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                // {
                //     {"userName",name},
                //     {"password",pwd}
                // });

                // 正确创建JSON请求
                var loginData = new
                {
                    userName = name,
                    password = pwd
                };

                var json = JsonConvert.SerializeObject(loginData);

                HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");

                // var response = client.PostAsync(loginUrl, httpContent).Result;

                // if (response.IsSuccessStatusCode)
                // {
                //     var result = response.Content.ReadAsStringAsync().Result;
                //     var loginResult = JsonConvert.DeserializeObject<ApiResult<LoginModel>>(result);

                //     if (loginResult.success == 200)
                //     {
                //         RequestUser.CurrentUser = loginResult.data;

                //         Form1 form = new Form1();
                //         form.Show();
                //         this.Hide();
                //     }
                //     else
                //     {
                //         MessageBox.Show(loginResult.message);
                //     }
                // }

                try
                {
                    var response = client.PostAsync(loginUrl, httpContent).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        var result = response.Content.ReadAsStringAsync().Result;
                        var loginResult = JsonConvert.DeserializeObject<ApiResult<LoginModel>>(result);

                        if (loginResult.success == 200)
                        {
                            RequestUser.CurrentUser = loginResult.data;

                            Form1 form = new Form1();
                            form.Show();
                            this.Hide();
                        }
                        else
                        {
                            MessageBox.Show(loginResult.message);
                        }
                    }
                    else
                    {
                        string errorContent = response.Content.ReadAsStringAsync().Result;
                        MessageBox.Show($"登录失败：{response.StatusCode} - {errorContent}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误：{ex.Message}");
                }
            }
        }


        public class LoginModel
        {
            /// <summary>
            /// 用户ID
            /// </summary>
            public long UserId { get; set; }

            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 真实姓名
            /// </summary>
            public string RealName { get; set; }

            /// <summary>
            /// 角色ID
            /// </summary>
            public string RoleId { get; set; }

            /// <summary>
            /// 角色名称
            /// </summary>
            public string RoleName { get; set; }

            /// <summary>
            /// 访问令牌
            /// </summary>
            public string Token { get; set; }

            /// <summary>
            /// 令牌过期时间（秒）
            /// </summary>
            public int ExpireIn { get; set; }
        }

    }
}